import React, { useState, useRef, useEffect } from 'react';
import { PlusOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons';
import { ProTable, ActionType, ProColumns } from '@ant-design/pro-components';
import { Button, Form, Input, message, Drawer, Switch, TreeSelect, Radio } from 'antd';
import { fetchMenus, createMenu, updateMenu, deleteMenu, queryAllMenuTree } from '@/services/ant-design-pro/system'; // 假设你已经创建了这些服务

interface MenuItem {
  id: number;
  componentPath: string;
  createId: string;
  createTime: string;
  description: string;
  icon: string;
  levels: number;
  menuCode: string;
  menuFlag: string;
  menuName: string;
  menuPath: string;
  menuRoute: string;
  newPageFlag: string;
  openFlag: string;
  operatorId: string;
  parentCode: string;
  parentName: string;
  permissionCharacter: string;
  prOnoff: number;
  prOnoffTime: string;
  routeName: string;
  routeParameter: string;
  sfCache: string;
  sfOutside: string;
  showStatus: string;
}

const MenuManagement: React.FC = () => {
  const [form] = Form.useForm();
  const actionRef = useRef<ActionType>();
  const [drawerVisible, setDrawerVisible] = useState(false);
  const [currentMenu, setCurrentMenu] = useState<MenuItem | null>(null);
  const [menuTree, setMenuTree] = useState<any[]>([]);
  const [tableKey, setTableKey] = useState('');


  const fetchMenuTree = async () => {
    try {
      const response = await queryAllMenuTree();
      if (response && response.data) {
        setMenuTree(response.data);
      }
    } catch (error) {
      message.error('加载菜单树数据失败');
    }
  };

  useEffect(() => {
    fetchMenuTree();
  }, []);

  const handleAdd = () => {
    setCurrentMenu(null);
    form.resetFields();
    setDrawerVisible(true);
  };

  const handleEdit = (record: MenuItem) => {
    setCurrentMenu(record);
    form.setFieldsValue(record);
    setDrawerVisible(true);
  };

  const handleDelete = async (id: number) => {
    try {
      await deleteMenu(id);
      message.success('删除成功');
      actionRef.current?.reload();
    } catch (error) {
      message.error('删除失败');
    }
  };

  const handleSubmit = async (values: MenuItem) => {
    try {
      if (currentMenu && currentMenu.id) {
        await updateMenu({ ...currentMenu, ...values });
        message.success('更新成功');
      } else {
        await createMenu(values);
        message.success('添加成功');
      }
      setDrawerVisible(false);
      actionRef.current?.reload();
    } catch (error) {
      message.error('操作失败');
    }
  };

  const columns: ProColumns<MenuItem>[] = [
    {
      title: '菜单名称',
      dataIndex: 'menuName',
      key: 'menuName',
    },
    {
      title: '菜单路由',
      dataIndex: 'menuRoute',
      key: 'menuRoute',
    },
    {
      title: '菜单图标',
      dataIndex: 'icon',
      key: 'icon',
    },
    {
      title: '操作',
      valueType: 'option',
      render: (text, record) => [
        <a key="edit" onClick={() => handleEdit(record)}>
          <EditOutlined /> 编辑
        </a>,
        <a key="delete" onClick={() => handleDelete(record.id)}>
          <DeleteOutlined /> 删除
        </a>,
      ],
    },
  ];

  return (
    <>
      <ProTable<MenuItem>
        key={tableKey}
        headerTitle="菜单管理"
        actionRef={actionRef}
        rowKey="id"
        search={false}
        toolBarRender={() => [
          <Button type="primary" key="add" onClick={handleAdd}>
            <PlusOutlined /> 添加
          </Button>,
        ]}
        expandable={{
          defaultExpandAllRows: true,
          childrenColumnName:'treeList',
          defaultExpandedRowKeys:[
            '1682'
          ]
        }}
        request={async (params) => {
          const response = await fetchMenus(params);
          setTableKey('tableKey')
          return {
            data: response.data,
            success: true,
            total: response.total,
          };
          
        }}
        columns={columns}
        pagination={{
          pageSize: 10,
        }}
      />
      <Drawer
        title={currentMenu ? '编辑菜单' : '添加菜单'}
        width={720}
        onClose={() => setDrawerVisible(false)}
        open={drawerVisible}
        bodyStyle={{ paddingBottom: 80 }}
        footer={
          <div
            style={{
              textAlign: 'right',
            }}
          >
            <Button onClick={() => setDrawerVisible(false)} style={{ marginRight: 8 }}>
              取消
            </Button>
            <Button onClick={() => form.submit()} type="primary">
              确认
            </Button>
          </div>
        }
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSubmit}
        >
          <Form.Item name="menuName" label="菜单名称" rules={[{ required: true, message: '请输入菜单名称' }]}>
            <Input />
          </Form.Item>
          <Form.Item name="menuRoute" label="菜单路由" rules={[{ required: true }]}>
            <Input />
          </Form.Item>
          <Form.Item name="componentPath" label="组件路径">
            <Input />
          </Form.Item>
          <Form.Item name="icon" label="菜单图标">
            <Input />
          </Form.Item>
          <Form.Item name="parentCode" label="父级菜单" rules={[{ required: true, message: '请选择父级菜单' }]}>
          <TreeSelect
              treeData={menuTree}
              fieldNames={{ label: 'menuName', value: 'menuCode', children: 'treeList' }}
              onSelect={(selectedKeys) => form.setFieldsValue({ parentCode: selectedKeys })}
            />
          </Form.Item>
          <Form.Item name="menuFlag" label="菜单类型" rules={[{required: true}]}>
          <Radio.Group>
            <Radio value={'0'}>目录</Radio>
            <Radio value={'1'}>菜单</Radio>
            <Radio value={'2'}>按钮</Radio>
          </Radio.Group>
          </Form.Item>
          {/* <Form.Item name="newPageFlag" label="是否打开新页面">
            <Switch checked={form.getFieldValue('newPageFlag')} />
          </Form.Item>
          <Form.Item name="openFlag" label="是否打开">
            <Switch checked={form.getFieldValue('openFlag')} />
          </Form.Item>
          <Form.Item name="sfCache" label="是否缓存">
            <Switch checked={form.getFieldValue('sfCache')} />
          </Form.Item>
          <Form.Item name="sfOutside" label="是否外联">
            <Switch checked={form.getFieldValue('sfOutside')} />
          </Form.Item>
          <Form.Item name="showStatus" label="显示状态">
            <Switch checked={form.getFieldValue('showStatus')} />
          </Form.Item> */}
        </Form>
      </Drawer>
    </>
  );
};

export default MenuManagement;